
var permits = {
    
    init: function() {
    
        
        permits.configureMenus();
        
        permits.configureTabs();
        
        permits.configureSearch();
        
        $("#btn_new_permit").click(function(e) {
            e.preventDefault();
            
            var url = $(this).attr("href");
            var query = "";
            
            $.post(url, query, function(data) {
                core.showFlyout({
                    title: "New Permit",
                    content: data,
                    height: '600',
                    load: function() {
                        
                        $("#permit_type").change(function() {
                            permits.configureAutoComplete();
                        });
                        
                        // if editing, configure the autocomplete immediately
                        permits.configureAutoComplete();
                        
                        permits.setupDatePickers();
                        permits.configureScheduleBlocks();
                    },
                    close: 'permits.displayNewPermit'
                });
            });
        });
        
        $(".buttons #edit-permit.active").live('click', function(e) {
            e.preventDefault();
            
            var url = $(this).data("url");
            var query = "permit_id=" + $(this).data("id");
            
            $.post(url, query, function(data) {
                core.showFlyout({
                    title: "Editing Permit",
                    content: data,
                    load: function() {
                        $("#permit_type").change(function() {
                            permits.configureAutoComplete();
                        });
                        
                        // if editing, configure the autocomplete immediately
                        permits.configureAutoComplete();
                        permits.setupDatePickers();
                        permits.configureScheduleBlocks();
                        
                        $("#flyout form input[type=submit]").val("Update Request");
                    },
                    
                    close: function() {
                        $("#permits_table tbody tr.selected").click();
                    }
                });
            });
        });
        
        $(".buttons #delete-permit.active").live('click', function(e) {
            e.preventDefault();
            
            if( !confirm('Delete Selected Permit and Move To Archive?') ) {
                return;
            }
            
            var url = $(this).data('url');
            var query = "permit_id=" + $(this).data('id');
            
            $.post(url, query, function() {
                permits.removeSelected('open');
            },'json');
        });
    },
    
    configureSearch: function() {
        function doSearch(url, term) {
            var query = "term=" + term+"&filter="+$("#search_term").val();
            $("#open_perms").html("Searching ...");
            
            $.ajax({
                url: url,
                data: query,
                //dataType: 'json',
                type: 'get',
                success: function(data) {
                    /*if( $("#tabs").tabs('option','selected') == 0 ) {
                        $("#open_perms").html(data);
                    }
                    
                    else {
                        $("#closed_perms").html(data);
                    }*/
                    
                    var panel = $(".ui-tabs-panel").get( $("#tabs").tabs('option','selected') );
                    $(panel).html(data);
                    
                    permits.setupGridBindings(panel);
                },
                error: function(xhr) {
                    console.log(xhr.responseText);
                }
            });
        }
        
        $("#search_term").change(function() {
            var option = this.options[this.selectedIndex];
             
            $("input.search").attr("placeholder", $(option).data('placeholder'));
        }).css({
            'font-size': '11px'
        });
        
        $("input.search").keyup(function(e) {
            if( e.keyCode == 13 ) {
                doSearch( $(this).data('url'), $(this).val() );
            }
        });
    },
    
    configureMenus: function() {
        
        $("#actions .menu li").click(function() {
            
            // only active menus should be processed
            if( !$(this).parents('.menu_button').hasClass('active') ) {
                return;
            }
            
            var menu = this;
            var el_id = menu.id;
            var permit_id = $(this).parents(".menu_button").data('id');
            
            var url = $(this).data('url');
            var type = $(this).data('type') == null ? 'json' : $(this).data('type');
            var query = "permit_id=" + permit_id;
            
            if( $(this).data('status') != null && $(this).data('status') != "" ) {
                query += "&status=" + $(this).data('status');
            }
            
            if( el_id == 'gen-forwarding-form' ) {
                if( $("#permits_table tr.selected .permit-number").text() == "" ) {
                    alert("Please Obtain and Enter Permit Number Before Generating Forwarding Form");
                    return;
                }
            }
            
            $.ajax({
                url: url,
                data: query,
                dataType: type,
                type: 'post',
                success: function(data) {
                    
                    switch(el_id) {
                        case 'send-to-caa':
                            core.showFlyout({
                                title: 'Send Request To CAA',
                                content: data,
                                load: function() {
                                    permits.setupCAAUI();
                                    core.setupButtonsAndMenus();
                                },
                                close: function() {
                                    $("#permits_table tr.selected .status").html('caa');
                                }
                            });
                            
                            break;
                            
                        case 'enter-permit':
                            core.showDialog({
                                title: 'Enter Permit Number',
                                content: data,
                                load: function() {
                                    $("#general_dialog .datetime").datetimepicker({ 
                                        showButtonPanel: false,
                                        showOn: "both",
                                        buttonImage: "../../img/core/ico-12.png",
                                        buttonImageOnly: true,
                                        minDate: -30,
                                        changeMonth: true,
                                        changeYear: true,
                                        dateFormat: 'yy-mm-dd',
                                        timeFormat: 'hh:mm'
                                    });
                                },
                                close: function(data) {
                                    $("#permits_table tr.selected .permit-number").html( data.Permit.permit_number );
                                    $("#permits_table tr.selected .status").html('approved');
                                    $("#permits_table tr.selected").click();
                                }
                            });
                            
                            break;
                            
                        case 'gen-forwarding-form':
                            core.showFlyout({
                                title: 'Preview Forwarding Form',
                                content: data,
                                load: function() {
                                    $(".flyout_content #print-form").click(function() {
                                        window.open( $(this).data('url') );
                                    });
                                    
                                    $(".flyout_content #download-form").click(function() {
                                        if( 'humane' in window ) {
                                            humane.info('Generating Forwarding Form PDF');
                                        }
                                        
                                        var $this = $(this);
                                        setTimeout(function() {
                                            window.location.href = $this.data('url');
                                        }, 1000);
                                        
                                    });
                                    
                                    $(".flyout_content #send-form").click(function() {
                                        $.get( $(this).data('url'), function(data) {
                                            core.showDialog({
                                                title: 'Sending Forwarding Form',
                                                content: data,
                                                width: 800,
                                                height: 550
                                            });
                                        });
                                        
                                    });
                                },
                                close: function(data) {
                                    $("#permits_table tr.selected .permit-number").html( data.Permit.permit_number );
                                    $("#permits_table tr.selected .status").html('approved');
                                    $("#permits_table tr.selected").click();
                                }
                            });
                            break;
                            
                        case 'attach_original_request':
                            core.showDialog({
                                title: 'Add/View Request Attachments',
                                content: data,
                                load: function() {
                                    Attachments.init({
                                        submit: function() {
                                            $(menu).click();
                                        }
                                    });
                                }
                            });
                            break;

                        case 'cancel-request':
                        case 'hold-request':
                        case 'close-request':
                            core.showDialog({
                                title: 'Change Request Status',
                                content: data,
                                width: 600,
                                height: 400,
                                close: function(data) {
                                    console.log(data);
                                    $("#permits_table tr.selected .status").html( data.status );
                                    
                                    if( data.status == "closed" ) {
                                        permits.removeSelected('open');
                                    }
                                }
                            });
                            break;
                    }
                },
                error: function(xhr) {
                    console.log(xhr.responseText);
                }
            });
        });
        
        $("#selected .menu li").click(function(e) {
            
            e.preventDefault();
            
            var ids = [];
            $("#permits_table tr input:checked").each(function() {
                ids.push( $(this).val() );
            });
            
            if( ids.length > 0 ) {
                if( !confirm("Are you sure you want to change the status of the selected permits?") ) {
                    return;
                }
            }
            
            else {
                alert("Please select permits to alter using the checkboxes");
                return;
            }
            
            var url = $("#selected.menu_button").data('url');
            var query = "status=" + $(this).data('status') + "&ids=" + ids;
            
            $.ajax({
                url: url,
                data: query,
                dataType: 'json',
                type: 'post',
                success: function(data) {
                    $("#permits_table tbody tr input:checked").each(function() {
                        if( ids.indexOf( $(this).val() ) > -1 ) {
                            if( data.open ) {    
                                permits.removeChecked('closed');
                            }
                    
                            else {
                                permits.removeChecked('open');
                            }
                        } 
                    });
                },
                error: function(xhr) {
                    console.log(xhr.responseText);
                }
            });
        });
    },
    
    configureAutoComplete: function() {
        
        var permit_type = $("#permit_type").val();
        
        if( permit_type.toLowerCase().indexOf("landing") > -1 || permit_type.toLowerCase().indexOf("stop") > -1 ) {
            $("#perm_loc_label").html("ICAO/IATA CITY OF LANDING RQST")
            $("input#permit_location").autocomplete('destroy');
            $("input#permit_location").autocomplete({
                source: $("#iata-auto-complete-source").val(),
                minLength: 2
            });
            
            $("#receiving_party_row").show();
        }
        
        else if( permit_type.toLowerCase().indexOf("overflight") > -1 ) {
            $("#perm_loc_label").html("COUNTRY OF OVRFLT. RQST");
            $("input#permit_location").autocomplete('destroy');
            $("input#permit_location").autocomplete({
                source: $("#country-auto-complete-source").val(),
                minLength: 2
            });
            
            $("#receiving_party_row").hide();
        }
    },
    
    configureTabs: function() {
        $( "#tabs" ).bind( "tabsload", function(event, ui) {
            permits.setupGridBindings(ui.panel);
        });
        
        $(".pane-footer li").live('click', function() {
            var url = $(this).data('url');
            
            $.ajax({
                url: url,
                type: 'get',
                success: function(data) {
                    if( $("table.fullwidth").hasClass('open') ) {
                        $("#open_perms").html(data);
                    }
                    
                    else {
                        $("#closed_perms").html(data);
                    }
                    
                    permits.setupGridBindings();
                },
                error: function(xhr) {
                    console.log(xhr.responseText);
                }
            }); 
        });
    },
    
    setupGridBindings: function(panel) {
        $(panel).find("#permits_table tbody tr").click(function() {
            $(".buttons li").addClass('active').data("id", $(this).data('id'));
            /*if( $(this).parents('#permits_table').hasClass('open') ) {
                $(".buttons li").addClass('active').data("id", $(this).data('id'));
            } else {
                $(".buttons li").removeClass('active');
            }*/

            var url = $(this).data("url");

            $.get(url, function(data) {
                $(".details_block .details_pane").html(data);
            });
        });
        
        $(panel).find("#permits_table tbody tr:first").addClass("selected").click();
    },
    
    removeSelected: function() {
        $("#permits_table tr.selected").remove();
        $(".buttons li").removeClass('active');
        
        var count = 1;
        $("#permits_table .numbers").each(function() {
            $(this).html(count++ + ".");
        });
    },
    
    removeChecked: function() {
        $("#permits_table tbody tr input:checked").each(function() {
            $(this).parents("tr").remove();
        });
        
        $(".buttons li").removeClass('active');
        
        var count = 1;
        $("#permits_table .numbers").each(function() {
            $(this).html(count++ + ".");
        });
    },
    
    showCAAInfo: function(authority_id) {
        var url = $("#authority_details_url").val();
        var query = "authority_id=" + authority_id;
        
        $.get(url, query, function(data) {
            $("#authority_address #address").html( data.AviationAuthority.address.replace("\n", "<br />") );
            $("#authority_address #telephone").html( data.AviationAuthority.telephone );
            $("#authority_address #fax").html( data.AviationAuthority.fax );
            $("#authority_address #date").html( $.datepicker.formatDate('dd MM, yy', new Date()) );
            $("#authority_address #email").html( data.AviationAuthority.email );
            
            $(".flyout_content .notice").hide();
        }, 'json');
    },
    
    setupDatePickers: function() {
        setTimeout(function() {
            
            $(".datetime").datetimepicker({ 
                showButtonPanel: false,
                showOn: "both",
                buttonImage: "../../img/core/ico-12.png",
                buttonImageOnly: true,
                minDate: -30,
                changeMonth: true,
                changeYear: true,
                dateFormat: 'yy-mm-dd',
                timeFormat: 'hh:mm'
            });
            
            $("#application_dt").datetimepicker({ 
                showButtonPanel: true,
                showOn: "both",
                buttonImage: "../../img/core/ico-12.png",
                buttonImageOnly: true,
                changeMonth: true,
                changeYear: true,
                dateFormat: 'yy-mm-dd',
                timeFormat: 'hh:mm:00'
            });
            
            $(".date_input input.date").datetimepicker({
                dateFormat: 'yy-mm-dd',
                timeFormat: 'hh:mm:ss',
                changeMonth: true,
                changeYear: true
            });
        
            $(".date_input input.location").autocomplete({
                source: $("#iata-auto-complete-source").val(), // specified in URLs element
                minLength: 2
            });
        }, 500);
    },
    
    configureScheduleBlocks: function() {
        $(".schedule_block .block_del_btn").live('click', function() {
            if( !confirm('Are you sure you would like to remove this Flight Schedule?')) {
                return;
            }
            
            var block = $(this).parent(".schedule_block");
            block.find(":input").attr("disabled", true);
            
            var url = $(this).data('url');
            $.post(url, function() {
                block.hide('slow', function() {
                    block.remove();
                });
            });
        });
        
        $("#block_add_btn").click(function() {
            var count = $(".schedule_block").length;
           
            var $row1 = $("<div />").addClass("date_input");
                $row1.append( $("<input />").addClass("cargo").attr({
                    type: 'text',
                    name: 'data[PermitSchedule][' + count + "][arr_flight_no]",
                    placeholder: "Flgt. No."
                }));
                $row1.append( $("<input />").addClass("date required").attr({
                    type: 'text',
                    name: 'data[PermitSchedule][' + count + "][arr_etd]",
                    placeholder: "ETD"
                }));
                $row1.append( $("<input />").addClass("location ui-autocomplete-input").attr({
                    type: 'text',
                    name: 'data[PermitSchedule][' + count + "][arr_origin]",
                    placeholder: "Origin"
                }));
                $row1.append( $("<input />").addClass("date required").attr({
                    type: 'text',
                    name: 'data[PermitSchedule][' + count + "][arr_eta]",
                    placeholder: "ETA",
                    required: ''
                }));
                $row1.append( $("<input />").addClass("location ui-autocomplete-input").attr({
                    type: 'text',
                    name: 'data[PermitSchedule][' + count + "][arr_dest]",
                    placeholder: "Dest",
                    required: ''
                }));
                
            var $row2 = $("<div />").addClass("date_input");
                $row2.append( $("<input />").addClass("cargo").attr({
                    type: 'text',
                    name: 'data[PermitSchedule][' + count + "][dept_flight_no]",
                    placeholder: "Flgt. No."
                }));
                $row2.append( $("<input />").addClass("date required").attr({
                    type: 'text',
                    name: 'data[PermitSchedule][' + count + "][dept_etd]",
                    placeholder: "ETD"
                }));
                $row2.append( $("<input />").addClass("location ui-autocomplete-input").attr({
                    type: 'text',
                    name: 'data[PermitSchedule][' + count + "][dept_origin]",
                    placeholder: "Origin"
                }));
                $row2.append( $("<input />").addClass("date required").attr({
                    type: 'text',
                    name: 'data[PermitSchedule][' + count + "][dept_eta]",
                    placeholder: "ETA"
                }));
                $row2.append( $("<input />").addClass("location ui-autocomplete-input").attr({
                    type: 'text',
                    name: 'data[PermitSchedule][' + count + "][dept_dest]",
                    placeholder: "Dest"
                }));
                
            var $schedule_block = $("<div />").addClass("schedule_block");
                $schedule_block.append( $row1 ).append( $row2 ).append( $("<button />").attr({type: 'button'}).addClass('block_del_btn').text("x") );
                
            $("#schedule_blocks").append( $schedule_block );
            
            permits.setupDatePickers();
        });
    },
    
    /**
     * Sets up the UI elements when the Send To CAA Request Form Is Loaded
     */
    setupCAAUI: function() {
        
        
        /**
         * Menu Button for the Print Form
         */
        $(".flyout_content #print_form_btn input").click(function() {
            var el_id = this.id;
            var permit_id = $(this).parents(".menu_button").data('permit-id');
            
            var url = $(this).data('url');
            var query = "permit_id=" + permit_id;
            var type = $(this).data('type') == null ? 'json' : $(this).data('type');
            
            switch(el_id) {
                case 'print-form':
                    window.open(url);
                    break;
                    
                case 'download-form':
                    window.location.href = url;
                    break;
                    
                case 'send-form':
                    $.ajax({
                        url: url,
                        data: query,
                        type: 'post',
                        success: function(data) {
                            core.showDialog({
                                title: 'Sending Permit To Selected CAA',
                                content: data,
                                width: 800,
                                height: 550
                            });
                        },
                        error: function(xhr) {
                            console.log(xhr.responseText);
                        }
                    });
                    
                    break;
            }
        });
        
        $(".flyout_content #save_send_btn").click(function() {
            
            if( $("#authorities").val() == "" ) {
                alert("Please Choose An Authority Before Saving The Request");
                return;
            }
            
            var params = {
                action: 'set_authority',
                permit_id: $("#permit_id").val(),
                authority_id: $("#authorities").val(),
                handler_id: $("#agents").val()
            };
            
            var url = $(this).data('url');
            $.ajax({
                url: url,
                data: params,
                dataType: 'json',
                type: 'post',
                success: function(data) {
                    $("#print_form_btn").css("display", "inline-block");
                    $("#permits_table tr.selected").find(".status").html(data.status);
                },
                error: function(xhr) {
                    console.log(xhr.responseText);
                }
            });
        });
        
        core.setupAutoComplete();
        
        $("#authorities").chosen().change(function() {
            permits.showCAAInfo( $("#authorities").val() );
            $("#print_form_btn").hide();
        });
        
        if( $("#authorities").val() != "" ) {
            $(".flyout_content .notice").hide();
            $("#print_form_btn").css("display", "inline-block");
        }
    },
    
    displayNewPermit: function() {
        $("#tabs").tabs('load', $("#tabs").tabs('option', 'selected'));
    },
    
    updatePermitDisplay: function(data) {
        console.log(data);
        $("#tabs").tabs('load', $("#tabs").tabs('option', 'selected'));
    }
};



$(document).ready(function() {
    permits.init();
});


